import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Modal } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { createUser, getAdminList, updateUser } from './service';
import type { CreateUserReq, TableListPagination, UserItem } from './data';
import type {} from './data';

const stateEnum = {
  true: {
    text: '启用',
    status: 'Success',
  },
  false: {
    text: '禁用',
    status: 'Default',
  },
};

const newUserData = {
  phone: '',
  password: '',
};

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<UserItem>();
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleAdd = async (fields: CreateUserReq) => {
    const hide = message.loading('正在添加');
    try {
      const resp = await createUser({ ...fields });
      hide();
      message.success('添加成功');
      Object.assign(newUserData, resp.data);
      console.log(newUserData);

      Modal.success({
        title: '管理员已创建成功',
        keyboard: false,
        okText: '我已记录',
        content: (
          <div>
            <p>
              账号：{resp.data.phone}
              <br />
              密码：{resp.data.password}
            </p>
          </div>
        ),
        onOk() {},
      });

      // setIsModalOpen(true);
      return true;
    } catch (error) {
      hide();
      return false;
    }
  };

  useEffect(() => {}, []);

  const columns: ProColumns<UserItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'text',
      width: 48,
      search: false,
    },
    {
      title: '手机',
      dataIndex: 'phone',
      tip: '管理员手机号',
      search: false,
    },
    {
      title: '姓名',
      dataIndex: 'real_name',
      valueType: 'text',
      search: false,
    },
    {
      title: '职位',
      dataIndex: 'position',
      valueType: 'text',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      valueType: 'text',
      search: false,
      valueEnum: stateEnum,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="userDisable"
          onClick={async () => {
            const hide = message.loading('正在处理');
            try {
              await updateUser(record.id, {
                real_name: record.real_name,
                position: record.position,
                is_active: !record.is_active,
              });
              hide();
              message.success('处理完毕');

              if (actionRef.current) {
                actionRef.current.reload();
              }

              return true;
            } catch (error) {
              hide();
              return false;
            }
          }}
        >
          {record.is_active == true ? '禁用' : '启用'}
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      {/* 主表格 */}
      <ProTable<UserItem, TableListPagination>
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建管理员
          </Button>,
        ]}
        request={(params) => getAdminList(params)}
        columns={columns}
        pagination={{
          pageSize: 1000,
          current: 1,
        }}
      />

      {/* 新建任务模态窗 */}
      <ModalForm
        title="新建管理员"
        width="400px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as CreateUserReq);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        initialValues={{}}
        modalProps={{ destroyOnClose: true }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '手机不能为空',
            },
          ]}
          width="md"
          name="phone"
          fieldProps={{ maxLength: 11, showCount: true }}
          label="手机"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '姓名不能为空',
            },
          ]}
          width="md"
          name="real_name"
          fieldProps={{ maxLength: 10 }}
          label="姓名"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '职务不能为空',
            },
          ]}
          width="md"
          name="position"
          fieldProps={{ maxLength: 10 }}
          label="职务"
        />
      </ModalForm>

      <Modal
        title="管理员创建成功"
        open={isModalOpen}
        destroyOnClose
        closable={false}
        okText="我已记录"
        onOk={() => setIsModalOpen(false)}
      >
        <p>账号：{newUserData.phone}</p>
        <p>密码：{newUserData.password}</p>
      </Modal>
    </PageContainer>
  );
};

export default TableList;
